<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <div>
    <div class="mainStyle" v-loading="loading">
      <div :style="{ width: leftWidth - 0.3 + '%' }">
        <el-card shadow="never" class="treeDiv card-shadow">
          <el-input size="small" v-model="matchName" placeholder="请输入关键字筛选" clearable style="margin-bottom: 10px">
            <template #append>
              <el-button size="small" :icon="Search" @click="filterNode" />
            </template>
          </el-input>
          <div class="treeStyle">
            <el-tree
              ref="materialTree"
              class="tree"
              :indent="0"
              :data="treeData"
              node-key="id"
              highlight-current
              :props="defaultProps"
              :default-expand-all="true"
              :current-node-key="currentChooseId"
              icon-class="el-icon-arrow-right"
              @node-click="treeSelect"
              @node-contextmenu="openMenu"
            >
              <template #default="{ data }">
                <el-tooltip
                  :disabled="tooltipVisible"
                  effect="dark"
                  :content="data.name + (data.versionNumber ? '/' + data.versionNumber : '')"
                  placement="top"
                >
                  <div style="display: flex; align-items: center" @mouseover="handleNodeMouseOver">
                    <img :src="getImageSrc(data)" alt="" style="height: 16px; width: 16px" />
                    <span> {{ data.name }} {{ data.versionNumber ? '/' + data.versionNumber : '' }}</span>
                  </div>
                </el-tooltip>
              </template>
            </el-tree>
            <!-- 自定义右键菜单 -->
            <div v-show="menuVisible" :style="menuStyle" class="custom-menu" ref="wrapper">
              <ul>
                <li @click="handleMenuClick('delete')">
                  <el-button size="small" link type="primary" icon="Delete">删除</el-button>
                </li>
              </ul>
            </div>
          </div>
        </el-card>
      </div>
      <div class="resizer" @mousedown.prevent="startResize"></div>
      <div class="rightDiv" :style="{ width: 100 - leftWidth + '%' }">
        <!-- <MaterialDetail ref="materialDetailRef" :treeData="detailTreeData" :canEdit="true" @handleEvent="handleEvent" /> -->
        <MaterialDetail
          v-if="dataAssetType == 'tree' && refreshing"
          ref="materialDetailRef"
          :treeData="detailTreeData"
          :canEdit="true"
          :modelId="currentChooseId"
          @handleEvent="handleEvent"
        />
        <div v-else-if="dataAssetType == 'table'" class="asset-table">
          <el-button type="primary" size="small" @click="addSection">新增</el-button>
          <el-table :data="assetTableData" border>
            <el-table-column v-for="td in filterTableColumns(assetTableData[0])" :key="td._index" :label="td.chinese + '(' + td.field + ')'" :prop="td.field" min-width="150" show-overflow-tooltip>
              <template #default="scope">
                <el-input v-if="pageType == 'EDIT' || pageType == 'ADD'" v-model="scope.row[td._index]['data']"></el-input>
                <span v-else>{{ scope.row[td._index]['data'] || '' }}</span>
              </template>
            </el-table-column>
            <!-- <el-table-column v-if="pageType == 'EDIT' || pageType == 'ADD'" label="操作" align="center" width="100" fixed="right">
              <template #default="scope">
                <el-button size="small" link type="primary" @click="addExtensionInfo(tab.data, scope.row)">添加</el-button>
                <el-button size="small" link type="primary" @click="removeExtensionInfo(tab.data, scope.$index)">删除</el-button>
              </template>
            </el-table-column> -->
            <el-table-column label="操作" align="center" width="100" fixed="right">
              <template #default="scope">
                <!-- <el-button size="small" link type="primary" @click="addSection(tab.data, scope.row)">添加</el-button> -->
                <el-button size="small" link type="primary" @click="editSection(scope.row)">编辑</el-button>
                <el-button size="small" link type="primary" @click="removeSection(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagenation">
            <el-pagination
              v-show="total > 0"
              layout="prev, pager, next,jumper"
              v-model:page="tableParams.pageNum"
              v-model:limit="tableParams.pageSize"
              :total="total"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </div>
    <AddSection 
      v-if="sectionVisible"
      :dialogVisible="sectionVisible"
      :fields="sectionFields"
      :type="sectionOperateType"
      @handleEvent="handleEvent"
    />
  </div>
</template>
<script setup>
import { Search } from '@element-plus/icons-vue';
import system from '@/assets/images/modelEstablish/system.svg';
import database from '@/assets/images/modelEstablish/database.svg';
import model from '@/assets/images/modelEstablish/model.svg';
import home from '@/assets/images/modelEstablish/home.svg';
import Scene from '@/assets/images/modelEstablish/Scene.svg';
import generalModel from '@/assets/images/modelEstablish/generalModel.svg';
import MaterialDetail from './MaterialDetail.vue';
import AddSection from './AddSection.vue';
import { ref, onMounted } from 'vue';
import { getMaterialDataList, getAssetTreeByDatabaseName, getMaterialFile, deleteMaterialListData, deleteMaterialNodeData, getMaterialTreeNew, getAssetDataList } from '@/api/material';
import { downloadFile } from '@/utils/index';
const emit = defineEmits(['handleEvent']);
const props = defineProps(['currentChooseId', 'databaseName']);
const tableData = ref([]);
const queryParams = ref({
  pageNum: 1,
  pageSize: 10
  // createBy: '',
});
const total = ref(0);
const refreshing = ref(false);
const loading = ref(false);
const conLoading = ref(false);
const materialRow = ref({});
const fieldList = ref([]);
const showView = ref(false);
const currentChooseId = ref(null);
const tableName = ref('');
const nodeContent = ref(null);
const menuVisible = ref(false);
const detailTreeData = ref([]);
const materialDetailRef = ref();
const matchName = ref('');
const materialTree = ref();
const tooltipVisible = ref(false);5021722
const dataAssetType = ref('');
const assetTableData = ref([]);
const pageType = ref('');
const sectionFields = ref([]);
const sectionOperateType = ref('');
const sectionVisible = ref(false);
const tableParams = ref({
  pageNum: 1, 
  pageSize: 10,
})
const menuStyle = ref({
  left: 0,
  top: 0
});
const defaultProps = {
  children: 'children',
  label: 'name'
};
const filterTableColumns = (cols) => {
  cols.forEach((item, index) => {
    item._index = index;
  })
  return cols.filter(col => col?.type !== 'info');
}
const treeData = ref([]);
const leftWidth = ref(20);
let startX = 0;
let startWidth = 0;
const startResize = (event) => {
  startX = event.clientX;
  startWidth = leftWidth.value;
  window.addEventListener('mousemove', onResize);
  window.addEventListener('mouseup', stopResize);
};

const onResize = (event) => {
  const dx = event.clientX - startX;
  const newWidth = startWidth + (dx / window.innerWidth) * 100;
  leftWidth.value = Math.max(10, Math.min(60, newWidth)); // 限制宽度在10%到90%之间
};

const stopResize = () => {
  window.removeEventListener('mousemove', onResize);
  window.removeEventListener('mouseup', stopResize);
};
watch(
  () => treeData.value,
  () => {
    setNodeAfterWidth();
  },
  { deep: true }
);
const setNodeAfterWidth = () => {
  if (!materialTree.value) return;
  nextTick(() => {
    document.querySelectorAll('.el-tree-node').forEach((node) => {
      if (node.querySelector('.el-tree-node__expand-icon.expanded')) {
        node.style.setProperty('--after-width', '18px');
      } else {
        node.style.setProperty('--after-width', '30px');
      }
    });
  });
};

const addSection = () => {
  let fields = assetTableData.value.filter(item => item.type !== 'info');
  sectionFields.value = fields && fields[0];
  sectionOperateType.value = 'ADD';
  sectionVisible.value = true;
}

const editSection = (row) => {
  sectionFields.value = row;
  sectionOperateType.value = 'EDIT';
  sectionVisible.value = true;
}

// 型材库删除
const removeSection = (row) => {
  ElMessageBox.confirm(`是否确认删除当前型材数据？`, `提示`, {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteMaterialNodeData({ tableName: row[0]?.tableName, objectId: row[0]?.objectId }).then((res) => {
      if (res.code == 200) {
        ElMessage({ showClose: true, message: '删除成功', type: 'success' });
        getDetailTreeData(currentChooseId.value);
      }
    });
  });
}

//左侧数结构
const filterNode = () => {
  // if (!value) return true;
  detailTreeData.value = [];
  if (materialDetailRef.value) {
    materialDetailRef.value.columns = [];
    materialDetailRef.value.fields = [];  
  }
  loadTreeData(matchName.value);
};
// 初始化图标
const getImageSrc = (data) => {
  if (data.type === 'root') {
    return home;
  } else if (data.type === 'database_1' || data.type === 'database_2') {
    return database;
  } else if (data.type === 'scene') {
    return Scene;
  } else if (data.type === 'system') {
    return system;
  } else if (data.type === 'model') {
    return model;
  } else if (data.type === 'common_model') {
    return generalModel;
  }
  return null;
};
const handleNodeMouseOver = (node) => {
  var target = node.target;
  let textLength = target.clientWidth;
  const nodeContent = target.closest('.el-tree-node__content');
  const containerWidth = nodeContent.clientWidth; // 获取包含 padding+border 的完整宽度
  console.log(textLength, containerWidth);
  if (textLength + 55 < containerWidth) {
    tooltipVisible.value = true;
  } else {
    tooltipVisible.value = false;
  }
};
// 右键点击
const openMenu = (event, data, node, element) => {
  if (!data.children || data.children.length === 0) {
    menuLevel.value = node.level;
    nodeContent.value = data;
    // 显示菜单
    menuVisible.value = true;
    // 阻止默认的右键菜单显示
    event.preventDefault();
    // 设置菜单的位置
    menuStyle.value.left = 210 + 'px';
    menuStyle.value.top = event.clientY - 82 + 'px';
  }
};

const handleMenuClick = () => {};
const resetQuery = () => {};
const getDataList = (id) => {
  let params = {
    ...queryParams.value,
    modelId: id
  };
  loading.value = true;
  getMaterialDataList(params)
    .then((res) => {
      if (res) {
        tableData.value = res.data.dataList;
        fieldList.value = res.data.fieldList;
        tableName.value = res.data.tableName;
        total.value = res.data.total || 0;
        loading.value = false;
        // tableData.value = mockJSON.data.dataList;
        // fieldList.value = mockJSON.data.fieldList;
        // total.value = 100;
      }
    })
    .catch(() => {
      loading.value = false;
    })
    .finally(() => {
      loading.value = false;
    });
};
const handleEvent = (prop) => {
  // showView.value = false;
  if (prop.type == 'resetTree') {
    getDetailTreeData(currentChooseId.value);
  } else if (prop.type =='cancel') {
    sectionVisible.value = false;
  } else if (prop.type =='success') {
    sectionVisible.value = false;
    getDetailTreeData(currentChooseId.value);
  }
}

// 装载材料树数据
const loadTreeData = (matchName) => {
  loading.value = true;
  getAssetTreeByDatabaseName({ dataBaseName: props.databaseName, matchName: matchName }).then((res) => {
    treeData.value = res.data;
    loading.value = false;
  });
};
// tree选择事件
const treeSelect = (selected) => {
  currentChooseId.value = selected.id;
  if (!selected.children || selected.children.length == 0) {
    (selected.type == 'model' || selected.type == 'common_model') && getDetailTreeData(selected.id);
    materialDetailRef.value.columns = [];
    materialDetailRef.value.fields = [];
  }
};
const handleCurrentChange = (num) => {
  tableParams.value.pageNum = num;
  getDetailTreeData(currentChooseId.value);
};
const getDetailTreeData = (modelId) => {
  conLoading.value = true;
  refreshing.value = false;
  // getMaterialTreeNew
  getAssetDataList({
    modelId,
    pageNum: tableParams.value.pageNum,
    pageSize: tableParams.value.pageSize
  }).then(res => {
    dataAssetType.value = res.data.showType;
    if (res.data.showType == 'tree') {
      detailTreeData.value = res.data?.treeResult;
      // detailTreeData.value.forEach(item => {
      //   deepHandleTree(item);
      // })
    } else if (res.data.showType == 'table') {
      assetTableData.value = res.data?.tableResult?.contentData || [];
      total.value = res.data?.tableResult?.totalSize || 0;
    }
    refreshing.value = true;
    conLoading.value = false;
  }).finally(() => {
    conLoading.value = false;
  })
};
const deepHandleTree = (obj) => {
  if (obj.children && obj.children.length > 0) {
    obj.children.push({
      data: '查看更多',
      type: 'info'
    })
    obj.children.forEach(child => {
      deepHandleTree(child);
    }); 
  }
}
onMounted(() => {
  loadTreeData('');
  setNodeAfterWidth();
});
onUnmounted(() => {
  window.removeEventListener('mousemove', onResize);
  window.removeEventListener('mouseup', stopResize);
});
</script>
<style lang="scss" scoped>
::deep .el-tree-node__expand-icon {
  display: none !important;
}
.mainStyle {
  padding: 20px;
  height: calc(100vh - 84px);
  display: flex;
}
.queryButtonClass {
  padding-bottom: 4px;
}
.card-shadow {
  box-shadow:
    0 2px 4px rgba(0, 0, 0, 0.1),
    /* 主阴影 */ 0 8px 16px rgba(0, 0, 0, 0.05); /* 环境光 */
  transition: box-shadow 0.3s ease;
}
.treeDiv {
  padding-top: 10px;
  height: 100%;
  overflow: auto;
  border-right: 1px solid #dddddd7a;
  margin-right: 5px;
  .treeStyle {
    padding-top: 10px;
  }
}
.resizer {
  position: relative;
  width: 0.3%;
  background-color: #d9d9d9;
  cursor: ew-resize;
  border-radius: 5px;
}
.preview_tableStyle {
  margin-top: 10px;
}
.previewDiv,
.queryFormDiv {
  border: 1px solid #dddddd7a;
  padding: 20px;
  .queryBtn {
    padding-left: 120px;
  }
  .parameterLayout {
    span {
      display: inline-block;
      width: 80px;
      padding-left: 5px;
    }
  }
}
.rightDiv {
  overflow: auto;
  margin-left: 5px;
  height: 100%;
}
@media (max-width: 1300px) {
  .previewDiv {
    .parameterLayout {
      :deep(.el-form-item--default .el-form-item__content) {
        width: auto;
      }
    }
  }
}
@media (max-width: 1300px) {
  :deep(.el-form-item--default .el-form-item__content) {
    width: 190px;
  }
  :deep(.el-form--inline .el-select) {
    width: 170px;
  }
  :deep(.el-form--inline .el-input) {
    width: 170px;
  }
}
@media (min-width: 1300px) {
  :deep(.el-form-item--default .el-form-item__content) {
    width: 260px;
  }
  :deep(.el-form--inline .el-select) {
    width: 240px;
  }
  :deep(.el-form--inline .el-input) {
    width: 240px;
  }
}
:deep(.el-form-item--default .el-form-item__label) {
  width: 120px;
  font-size: 12px;
  font-weight: normal;
}
:deep(.el-collapse .el-collapse-item__content) {
  padding: 0;
}
:deep(.el-table--default) {
  height: 100%;
}
:deep(.el-form--inline .el-form-item) {
  min-width: 370px;
  margin-right: 0;
}
:deep(.el-tree-node__label) {
  font-size: 12px;
  color: #606266;
}
:deep(.el-form .el-form-item__label) {
  font-size: 12px;
  font-weight: normal;
}
.marquee {
  width: 300px;
  // overflow: hidden;
  white-space: nowrap;
  // border: 1px solid #ccc;
}
.marquee span {
  display: inline-block;
  padding-left: 0; /* 初始位置在右侧 */
  &:hover {
    animation: marquee 10s linear infinite;
  }
}
@keyframes marquee {
  0% {
    transform: translateX(0);
  }
  100% {
    transform: translateX(-100%);
  }
}
/* 树形结构节点添加连线 */
:deep .tree {
  .el-tree-node {
    position: relative;
    padding-left: 10px;
    /* 缩进量 */
  }

  .el-tree-node__children {
    padding-left: 15px;
    /* 缩进量 */
  }

  /* 竖线 */
  .el-tree-node::before {
    content: '';
    height: 100%;
    width: 1px;
    position: absolute;
    left: -3px;
    top: -26px;
    border-width: 1px;
    border-left: 1px dashed #52627c;
  }

  /* 当前层最后一个节点的竖线高度固定 */
  .el-tree-node:last-child::before {
    height: 40px;
    /* 可以自己调节到合适数值 */
  }

  /* 横线 */
  .el-tree-node::after {
    content: '';
    width: var(--after-width, 30px);
    height: 20px;
    position: absolute;
    left: -3px;
    top: 13px;
    border-width: 1px;
    border-top: 1px dashed #52627c;
  }

  /* 去掉最顶层的虚线，放最下面样式才不会被上面的覆盖了 */
  & > .el-tree-node::after {
    border-top: none;
  }

  & > .el-tree-node::before {
    border-left: none;
  }

  /* 展开关闭的icon */
  .el-tree-node__expand-icon {
    font-size: 12px;
    /* 叶子节点（无子节点） */
    &.is-leaf {
      color: transparent;
      /* 也可以去掉 */
      // display: none;
      width: 12px;
    }
  }
}
.pagenation {
  display: flex;
  justify-content: end;
  margin-top: 10px;
}
</style>
